package cn.itcast.springmvc.controller;

import cn.itcast.springmvc.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by User on 2018/1/7.
 */
@Controller
@RequestMapping("params")
public class ReceiveParamsController {

    @RequestMapping("hello")
    public String hello(Model model, ModelMap modelMap, Map map, ModelAndView modelAndView){

        return "hello";
    }

    @RequestMapping("login")
    public String login(Model model, String username, @RequestParam("password") String password){

        System.out.println("username:" + username + ", password:" + password);

        return "hello";
    }

    @RequestMapping("list")
    public String list(Model model, @RequestParam(value = "users" ,required = false) List<User> users){

        System.out.println(users);

        return "hello";
    }

    @RequestMapping("json-list")
    public String jsonList(Model model, @RequestBody List<User> users){

        for (User user: users) {
            System.out.println(user);
        }
        return "hello";
    }

    @ResponseBody
    @RequestMapping("findAllUser")
    public List<User> findAll(){

        List<User> list = new ArrayList<>();
        User user = new User();
        user.setName("张三");
        user.setPassword("123");
        User user2 = new User();
        user2.setName("李四");
        user2.setPassword("123");

        list.add(user);
        list.add(user2);


        return list;
    }

    @RequestMapping("model")
    public String model(Model model, ModelMap modelMap){
        model.addAttribute("msg", "springmvc接收参数与数据绑定：特定内置参数");
        modelMap.addAttribute("msg", "springmvc接收参数与数据绑定：特定内置参数2");
        return "hello";
    }

    @RequestMapping("upload")
    public String upload(Model model, @RequestParam("file")MultipartFile file) throws IOException {
        if (file!=null) {
            file.transferTo(new File("c:\\tmp\\" + file.getOriginalFilename()));
        }

        return "redirect:/success.html";
    }
}
